package rsschart.charter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class CharterFactory {
	
	private static Map charters;
	
	//-- to do: build this string when initialized 
	private static String chartTypes;
	
	/**
	 * Sets the charter type to Charter class map
	 * Should this method be static or could different clients initialize it?
	 * @param props
	 */
	public static void load(Properties props) {
		Set keys;
		String key;
		Iterator iter;
		if (charters==null) {
			charters = new HashMap();
		}
		keys = props.keySet();
		if (keys != null) {
			iter = keys.iterator();
			while (iter.hasNext()) {
				key = (String)iter.next();
				charters.put(key, props.get(key));
			}
		}
	}
	
	
	
	
	public static Charter getCharter(String chartType) throws Exception {
		
		Charter chart;
		String charterClass;
		
		if (charters==null) {
			throw new Exception("CharterFactory not initialized");
		}
		
		if (charters.containsKey(chartType)) {
			charterClass = (String)charters.get(chartType);
			
			
			try {
				chart = (Charter) Class.forName(charterClass).newInstance();
				return chart;
			}
			catch (ClassCastException cce) {
				throw new Exception("Class " + charterClass + " does not implement Charter interface");
			}
			catch (Exception e) {
				throw new Exception("Exception creating charter: " + charterClass + "; " + e.getMessage());
			}
		}
		else {
			throw new Exception("No charter defined for chart type: " + chartType); 
		}
	
		
		
		/**
		if (chartType.equalsIgnoreCase("bar")) {
			chart = new BarChart();
		}
		else if (chartType.equalsIgnoreCase("line")) {
			chart = new LineChart();
		}
		else if (chartType.equalsIgnoreCase("pie")) {
			chart = new PieChart();
		}
		else if (chartType.equalsIgnoreCase("groupBar")) {
			chart = new GroupBarChart();
		}
		else if (chartType.equalsIgnoreCase("stackBar")) {
			chart = new StackBarChart();
		}
		else {
			//-- to do: make rsschart exception class hierarchy
			throw new Exception("Undefined chart type: " + chartType + ". Expected: bar|line|pie|groupBar|stackBar");
		}
		**/

		
	}

}
